/*
 * RegistrarVenda.java
 *
 * Created on 2 de Fevereiro de 2008, 00:13
 */

package sisvenda;



import java.sql.Date;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sisvenda.clientes.ClienteBean;
import sisvenda.clientes.ClienteControl;
import sisvenda.produtos.ProdutoBean;
import sisvenda.produtos.ProdutoControl;
import sisvenda.vendas.VendasBean;
import sisvenda.vendas.VendasControl;

/**
 *
 * @author  Cl�udio
 */
public class RegistrarVenda extends javax.swing.JFrame {
    
    DefaultTableModel tmVendas = new DefaultTableModel(null, new String[] {"Produto","Quantidade","Valor"});
    List<ClienteBean> clientes;
    List<ProdutoBean> produtos;
    List<VendasBean> venda = new ArrayList<VendasBean>();
    double total = 0;
    
    /** Creates new form RegistrarVenda */
    public RegistrarVenda() {
        initComponents();
        listarClientes();
        listarProdutos();
    }
    
    private void listarProdutos(){
        ProdutoControl prd = new ProdutoControl();
        produtos = prd.listarProdutos("%%");
        cbProdutos.removeAllItems();
        for (int i = 0; i < produtos.size(); i++){
            cbProdutos.addItem(produtos.get(i).getNome());
        }
    }
    
    private void listarClientes(){
        ClienteControl cli = new ClienteControl();
        clientes = cli.listarClientes("%%");
        cbClientes.removeAllItems();
        for (int i = 0; i < clientes.size(); i++){
            cbClientes.addItem(clientes.get(i).getNome());
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" C�digo Gerado ">//GEN-BEGIN:initComponents
    private void initComponents() {
        cbClientes = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cbProdutos = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        ftfQuantidade = new JFormattedTextField(NumberFormat.getNumberInstance());
        jScrollPane1 = new javax.swing.JScrollPane();
        tbVendas = new javax.swing.JTable();
        btIncluirProduto = new javax.swing.JButton();
        btFinalizar = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        ftfDesconto = new JFormattedTextField(NumberFormat.getNumberInstance());
        jLabel5 = new javax.swing.JLabel();
        ftfTotal = new JFormattedTextField(NumberFormat.getNumberInstance());

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Venda");
        cbClientes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel1.setText("Cliente:");

        jLabel2.setText("Produto:");

        cbProdutos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("Quant.:");

        tbVendas.setModel(tmVendas);
        jScrollPane1.setViewportView(tbVendas);

        btIncluirProduto.setText("Incluir");
        btIncluirProduto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIncluirProdutoActionPerformed(evt);
            }
        });

        btFinalizar.setText("Finalizar");
        btFinalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFinalizarActionPerformed(evt);
            }
        });

        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        jLabel4.setText("Desconto:");

        jLabel5.setText("Total:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cbProdutos, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(btIncluirProduto)
                                        .addComponent(ftfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(ftfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(ftfDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(103, 103, 103)
                        .addComponent(btFinalizar)
                        .addGap(28, 28, 28)
                        .addComponent(btCancelar)))
                .addGap(30, 30, 30))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbProdutos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ftfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3)
                .addComponent(btIncluirProduto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftfDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ftfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btFinalizar)
                    .addComponent(btCancelar))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        cancelarVenda();
    }//GEN-LAST:event_btCancelarActionPerformed

    private void cancelarVenda(){
        while (tmVendas.getRowCount() > 0){
            tmVendas.removeRow(0);
        }
        total = 0;
        ftfTotal.setValue(0);
        venda.clear();
        this.dispose();
    }
    
    private void btFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFinalizarActionPerformed
        cadastrarVenda();
    }//GEN-LAST:event_btFinalizarActionPerformed

    private void cadastrarVenda(){
        if (venda.size() == 0){
            JOptionPane.showMessageDialog(this, "Inclua pelo menos um produto!");
        } else {
            try {
                VendasControl vc = new VendasControl();
                SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date d = new java.util.Date();
                Date data = Date.valueOf(formato.format(d));
                int codigo = vc.buscarCodigoUltimaVenda() + 1;
                for (int i = 0; i < venda.size(); i++){
                    venda.get(i).setCodigoCliente(clientes.get(cbClientes.getSelectedIndex()).getCodigo());
                    venda.get(i).setDataVenda(data);
                    venda.get(i).setCodigo(codigo);
                    vc.cadastrarVenda(venda.get(i));
                }
                JOptionPane.showMessageDialog(this, "Venda cadastrada com sucesso!");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao cadastrar Venda!");
            }
        }
    }
    
    private void btIncluirProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIncluirProdutoActionPerformed
        incluirProduto();
    }//GEN-LAST:event_btIncluirProdutoActionPerformed

    private void incluirProduto(){
        if (verificarQuantidade()){
            VendasBean vb = new VendasBean();
            vb.setCodigoProduto(produtos.get(cbProdutos.getSelectedIndex()).getCodigo());
            vb.setQuantidade(Integer.parseInt(String.valueOf(ftfQuantidade.getValue())));
            venda.add(vb);
            String produto = produtos.get(cbProdutos.getSelectedIndex()).getNome();
            String quantidade = String.valueOf(ftfQuantidade.getValue());
            String valor = String.valueOf(produtos.get(cbProdutos.getSelectedIndex()).getValor() * Integer.parseInt(quantidade));
            String [] campos = new String [] { produto, quantidade, valor};
            tmVendas.addRow(campos);
            total += Double.parseDouble(valor);
            ftfTotal.setValue(total);
        } else {
            JOptionPane.showMessageDialog(this, "Quantidade inv�lida!");
            ftfQuantidade.requestFocus();
        }
    }
    
    private boolean verificarQuantidade(){
        try {
            if (Integer.parseInt(String.valueOf(ftfQuantidade.getValue())) > 0){
                return true;
            }
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        return false;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RegistrarVenda().setVisible(true);
            }
        });
    }
    
    // Declara��o de vari�veis - n�o modifique//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btFinalizar;
    private javax.swing.JButton btIncluirProduto;
    private javax.swing.JComboBox cbClientes;
    private javax.swing.JComboBox cbProdutos;
    private javax.swing.JFormattedTextField ftfDesconto;
    private javax.swing.JFormattedTextField ftfQuantidade;
    private javax.swing.JFormattedTextField ftfTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbVendas;
    // Fim da declara��o de vari�veis//GEN-END:variables
    
}
